<?php
defined('OA_LIB_PATH') || define('OA_LIB_PATH', '/opt/op/OALib');

require_once OA_LIB_PATH . '/util/config/Config.php';
require_once OA_LIB_PATH . '/inner/stat/OaGearmanWorker.php';

class OaLogWorker extends OaGearmanWorker
{
    
    function __construct($logger = null)
    {
        $jobServers = Oa_Util_Config::getConfig('job_servers');
        parent::__construct($jobServers, $logger);
    }
    
    public function run()
    {
        $this->addFunction("log", array($this, 'log'));
        $this->addFunction("log_multi", array($this, 'logMulti'));
        parent::run();
    }
    
    public function log($job)
    {
        $workload = $job->workload();
        $this->_logger->debug("do task: task-log, workload-$workload");
        $workload = json_decode($workload, true);
        if ($workload === false) {
            $this->_logger->err("get workload failed");
            return false;
        }
        $this->_logToFile($workload['type'], $workload['message']);
        return true;
    }
    
    public function logMulti($job)
    {
        $workload = $job->workload();
        $this->_logger->debug("do task: task-log_multi, workload-$workload");
        $workload = json_decode($workload, true);
        if ($workload === false) {
            $this->_logger->err("get workload failed");
            return false;
        }
        $messages = array();
        foreach ($workload as $w) {
            $w = json_decode($w, true);
            $type = $w['type'];
            $message = $w['message'];
            if (isset($messages[$type])) {
                $messages[$type] .= $message;
            } else {
                $messages[$type] = $message;
            }
        }
        foreach ($messages as $type => $message) {
            $this->_logToFile($type, $message);
        }
        return true;
    }
    
    private function _logToFile($type, $message)
    {
        $type = str_replace(array('/', '\\', '.'), '', $type);
        $dir = "/var/log/stat/$type/" . date('Ym');
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $filename =  "$dir/{$type}_" . date('Ymd') . ".log";
        $fp = fopen($filename, 'a');
        flock($fp, LOCK_EX);
        $result = fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);
        if ($result === false) {
            return false;
        } else {
            return true;
        }
    }
}
?>